<?php

namespace app\index\controller\tan;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\index\controller\Product;
/**
 * 商家旗下顾客
 */
class Customer extends Controller
{
    use UploadFileTrait;
    /**
     * 刘家腾
     * 2018-5-18 改
     *谭金星
     *2018-4-
     * @param      \think\Request  $Request  The request
     */
    public function index(Request $Request)
    { 
        $user_info=Session::get("user");

        $get=$Request->post();

        Ret::IfNoTrue($this->validate($get, [
            "trackdate|跟进时间"=>"date",
            "goshopdate|到店时间"=>"date",
            "createtime|创建时间"=>"date",
            "state2|到店状态"=>"in:2,1",
        ]),10022);

        if($user_info['is_business']!=0){
            $where=[
                    "u.is_customer"=>1,
                    "u.state"=>0,
//                    "i.state"=>0,
                    "c.business_id"=>$user_info['id'],
                ];
        }elseif($user_info['shop']!=0){
            $where=[
                    "u.is_customer"=>1,
                    "u.state"=>0,
//                    "i.state"=>0,
                    "c.store_id"=>$user_info['id'],
                ];
        
        }elseif($user_info['is_staff']!=0){
            $storeinfo=$this->getbusinessid($user_info['id']);
            $where=[
                    "c.sales_id"=>$user_info['id'],
                    "u.is_customer"=>1,
                    "u.state"=>0,
//                    "i.state"=>0,
                    "c.store_id"=>$storeinfo['store_id'],
                ];
        }

        $data=Db::table("customer")->alias("c")
//                ->join("user_info i","c.user_id=i.user_id","left")
                ->join("users u","c.user_id=u.id","left")
                ->join("business b","c.business_id=b.business_id","left")
                ->join("store s","c.store_id=s.user_id","left")
                ->join("customer_log l","c.user_id=l.user_id","left")
                ->join("staff st","c.sales_id=st.user_id","left")
                ->join("users uu","uu.id=c.sales_id","left")
                ->where($where)
                ->where(function($query) use ($get){
                    $query->where(Eliminate::ESearch([ "c.store_id", "c.sales_id","l.follow_type","l.state2" ], $get)); 
                    if(! empty($get["createtime"])){
                        $query->where("u.createtime",">=" ,$get['createtime'].' 00:00:00');#客户添加时间
                        $query->where("u.createtime","<=" ,$get['createtime'].' 23:59:59');
                    }
                    if(! empty($get["goshopdate"])){
                        $query->where("l.goshopdate",">=" ,$get['goshopdate']);#最新跟进时间
                    }
                    if(! empty($get["trackdate"])){
                        $query->where("l.trackdate",">=" ,$get['trackdate']);#最近到店时间
                    }
                    if(!empty($get['source'])){
                        $query->where("l.source","like","%{$get['source']}%");#来源
                    }
                    if(! empty($get["name"])){
                        $query->where("l.brand_demand","like","%{$get["name"]}%")  #需求品牌
                                ->whereOr("u.name","like","%{$get["name"]}%");#姓名
                    }
                })
                    /* 
                     * 该sql语句条件
                     *  WHERE `u`.`higherups` = 1 AND `u`.`state` = 0 AND `i`.`state` = 0 
                     *      AND ( `c`.`store_id` = '1' AND `c`.`createtime` > '2018-4-26' ) 
                     *      AND ( `l`.`brand_demand` LIKE '%lv%' OR `u`.`name` LIKE '%lv%' )
                     */
                ->field([
                    "c.id",
                    "u.name",#顾客名称
                    // "u.grade",#会员等级
                    // "u.is_address",#收货地址
                    "u.phone",#手机
                    // "u.card_balance",//会员卡余额
                    // "u.enjoy_currency",//芮享币
                    // "u.remark",//
                    // "i.topimageurl",//用户头像
                    // "i.age",//
                    // "i.hobby",
                    // "i.qq",
                    // "i.sex",
                    "c.is_toshop",//是否到店
                    "b.business_name",//商铺名称
                    "s.store_name",//店铺名称
                    "l.source",//来源
                    "l.brand_demand",//新加品牌标签
                    "l.follow_type",//回访类型
                    "l.brand_id",//选择的原本品牌标签ID
                    "l.follow_content",//跟进记录
                    "l.trackdate", // 跟进时间
                    "l.goshopdate",
                    "c.createtime",//创建时间
                    "c.store_id",//所属门店id
                    "c.sales_id",//销售ID(员工表userID)
                    "st.name as sale_name",//销售名称
                    "c.remark", // 备注
                    "c.next_visit", // 下次回访时间
                    "c.state", // 是否禁用
                ])
                ->order("u.id desc")
                ->select();
        $brand_demand = [];
        foreach ($data as $key => $value) {
            if($value['store_name']==''){
                $data[$key]['store_name']=$value['business_name'];
            }
            if($value['brand_demand']!=null){
               $brand_demand = json_decode($value['brand_demand'],true);
            }
            if($value['sale_name'] == ''){
                $user = Db::table('users')->where('id',$value['sales_id'])->find();
                if($user['is_business'] != 0){ // 销售员是商户
                    $data[$key]['sale_name'] = $user['name'];
                }elseif($user['shop'] != 0){
                    $data[$key]['sale_name'] = $user['name'];
                }
            }
            $list = [];
            if($value['brand_id'] != null){

               $brand_id = $this->get_brandtags(json_decode($value['brand_id'],true));
               

               foreach ($brand_id as $k => $v) {
                   $list[$k]=$v['title'];
                }

            }
            if(empty($brand_demand)){
                $brand_demands=$list;
            }elseif(empty($list)){
                $brand_demands=$brand_demand;
            }else{
                $brand_demands=array_merge($brand_demand,$list);
            }
            $data[$key]['brand_demand']=$brand_demands;

             if(! empty($get["brand_demand"]) && !in_array($get["brand_demand"], $data[$key]['brand_demand'])){
                unset($data[$key]);
            }
            
        }
        $get['page'] = isset($get['page']) ? $get['page'] : 1;
        return ['code' => 666, 'msg' => 'ok', 'data' => ['count' => count($data), 'list' => array_slice($data,20*($get['page']-1),20)]];
        
    }

     /**
     * 刘家腾
     * 2018-4-28
     * @return    员工 获取商户id
     * 
     */
    public function getbusinessid($user_infoid=0)
    {
      return Db::table('staff')
            ->where(["user_id"=>$user_infoid])
            ->where(["state"=>0])
            ->field('business_id,store_id')
            ->select();
    }
    
    /**
     * 刘家腾
     * 2018-4-25
     * @return     门店 获取商户id
     * 
     */
    public function get_businessid($user_infoid=0)
    {
      return Db::table('store')
            ->where("user_id",$user_infoid)
            ->where("state",0)
            ->value('business_id');
    }
    /**
     * 刘家腾
     * 2018-5-21
     * @return     查询用户是否已经存在
     * 
     */
    public function is_phone($phone=0)
    {
        
      return Db::table('users')
            ->where("phone",$phone)
            ->where("state",0)
            ->count();
    }

    /**
     * 刘家腾
     * 2018-5-23
     * 获取品牌类目名称
     * @param      string  $value  The value
     */
    public function get_brandtags($value=[])
    {
        return Db::table('systematics')
            ->where('id','in',$value)
            ->field("title")
            ->order('id desc')
            ->select();

    }

    /**
     * jason
     * 2018-5-24
     * 获取来源列表
     * 
     */
    public function get_resources()
    {
        $sources = Db::table('customer_log')
                    ->field("source")
                    ->select();
        $values = array_map(function($s){return $s['source']; }, $sources);

        return['code' => 666, 'msg' => 'sources list', 'data' => array_values(array_unique($values))];

    }


    /**
     * 刘家腾
     * 2018-5-21
     * 获取品牌表签
     */
    public function post_brandlabel()
    {
        $user_info=Session::get("user");

        $systematics = Db::table('systematics')
            ->where(["system_id"=>$user_info['system_id'], "type"=>2])
            ->order('id desc')
            ->select();

        return ['code' =>666,'msg' => '获取品牌表签成功', 'data' => $systematics];
    }

    public function save(Request $Request){

        $validate=[
            // "store_id|门店归属"=>"require|number",
            "name|名称"=>"require|chsDash",
            "sex|性别"=>"in:0,1,3",
            "age|年龄"=>"number|between:1,150",
            "phone|电话"=>"require|number|max:11|^1[0-9]{10}$",
            "remark|备注"=>"max:100",
            // "brand_id|品牌id"=>"require",
//            "sales_id|销售员"=>"require|number",
            // "brand_demand|品牌需求"=>"require",
//            "follow_type|更进类型"=>"require",
//            "wechat|微信账号"=>"max:20",
        ];
        
        $post       = $Request->post();
        $validate   = $this->validate($post, $validate);
        ReturnData::IfTrue($validate, 10100);

        $is_phone   = $this->is_phone($post['phone']);
        if($is_phone != 0){
            ReturnData::err(10101,[],"手机号已经存在，不能重复添加！");
        }

        $user_info=Session::get("user");
        if($user_info['is_business']!=0)
        {
            $business_id    = $user_info['id'];
            $store_id       = $post['store_id']=='' ? 0 : $post['store_id'];
            $staff_id       = $post['sales_id']=='' ? $user_info['id'] : $post['sales_id'];
        }elseif($user_info['shop']!=0)
        {
            $bs_info=$this->get_businessid($user_info['id']);
            $business_id=$bs_info;
            $store_id=$user_info['id'];
            $staff_id       = $post['sales_id']=='' ? $user_info['id'] : $post['sales_id'];

        }elseif($user_info['is_staff']!=0)
        {
            $bs_info=$this->getbusinessid($user_info['id']);
            $business_id=$bs_info['business_id'];
            $store_id=$bs_info['store_id'];
            $staff_id       = $post['sales_id']=='' ? $user_info['id'] : $post['sales_id'];
        }

        $post['topimageurl']= $Request->post("topimageurl"); 
        // 启动事务
        Db::startTrans();
        try{
            $id=  Db::table("users")->insertGetId([
                "system_id"=>$user_info['system_id'],
                "name"=>$post['name'],
                "is_business"=>0,
                "state"=>0,
                "grade"=>1,
                "openid"=>$Request->post('openid'),
                "phone"=>$post['phone'],
                "card_balance"=>$Request->post('card_balance'),
                "remark"=>$Request->post('remark'),
                "enjoy_currency"=>$Request->post('enjoy_currency'),
                "createtime"=>date("Y-m-d H:i:s"),
                "higherups"=>Session::get("user.id"),
                "is_customer"=>1,
            ]); 
            if(! $id){
                Db::rollback();
                ReturnData::err(10101);
            }
            Db::table("user_info")->insert([

                "user_id"=>$id,
                "name"=>$post['name'],
                "age"=>$Request->post("age"),
                "sex"=>$Request->post("sex"),
                "wechat"=>$Request->post("wechat"),
                "occupation"=>$Request->post("occupation"),
                "residence"=>isset($post["residence"]) ? json_encode($post["residence"]) : null,
                "hobby"=>$Request->post("hobby"),
                "alipay"=>$Request->post("alipay"),
                "wechat"=>$Request->post("wechat"),
                "createtime"=>date("Y-m-d H:i:s"),
                "topimageurl"=>$post['topimageurl']
            ]); 
            Db::table("customer")->insert([
                "business_id"=>$business_id,
                "system_id"=>$user_info['system_id'],
                "store_id"=>$store_id,
                "sales_id"=>$staff_id,
                "user_id"=>$id,
                "state"=>0,
                "createtime"=>date("Y-m-d H:i:s"),
                "remark"=>$Request->post('remark')
            ]);
            
            Db::table("customer_log")->insert([
                "user_id"=>$id,
                "brand_demand"=>json_encode($post['brand_demand']),
                "brand_id"=> json_encode($post['brand_id']),
                "source"=>$Request->post("source"),
                "follow_type"=>$post['follow_type'],
                "follow_content"=>$post['follow_content'],
                "state"=>0,
                "createtime" => date("Y-m-d H:i:s"),
                "system_id" => $user_info['system_id'],
                "business_id" =>$business_id,
                "store_id"    => $store_id,
                "sales_id"=>$staff_id
            ]);
            Db::table("bankcard")->insert([
                "user_id"=>$id,
                "bankcard_id"=>$Request->post("bankcard_id"),
                "opening_bank_address"=>$Request->post("opening_bank_address"),
                "createtime"=>date("Y-m-d H:i:s"),
                "phone"=>$Request->post("phone"),
                "opening_bank"=>$Request->post("opening_bank"),
            ]);
            // 提交事务
            Db::commit();    
            ReturnData::ok();
        } catch (\Exception $e) {
            // 回滚事务
            ReturnData::err(10102,[],$e->getMessage());
            Db::rollback();
        }
    }

    /**
     * 获取客户详情
     *
     * @param  int  客户的 user id
     * @return \think\Response
     */
    public function get(Request $request)
    {
        if(! isset($request->post()['id'])){
            ReturnData::err(10100,[],'id 不能为空！'); 
        }
        $customerId = $request->post()['id'];

        $customer = Db::table('customer')
                    ->alias('c')
                    ->join('customer_log cl', 'c.user_id = cl.user_id','LEFT')
                    ->join('store s', 'c.user_id = s.user_id','LEFT')
                    ->join('staff st','c.sales_id = st.user_id','LEFT')
                    ->join('users u', 'c.user_id = u.id','LEFT')
                    ->join('user_info ui', 'c.user_id = ui.user_id','LEFT')
                    ->join('bankcard b', 'c.user_id = b.user_id','LEFT')
                    ->where(['c.id' => $customerId])
                    ->field('c.*,'
                            . 's.store_name,'
                            . 'u.name, '
                            . 'ui.sex, '
                            . 'u.phone,'
                            . 'cl.brand_demand,'
                            . 'cl.brand_id,cl.follow_type,cl.follow_content,cl.source,'
                            . 'ui.residence,ui.wechat,ui.alipay,'
                            . 'b.bankcard_id,'
                            . 'st.name sale_name'
                            )
                    ->find();
        
        if($customer['store_id'] == 0){
            $business = Db::table('business')->where('business_id',$customer['business_id'])->find();
            $customer['store_name'] = $business['business_name'];
            $customer['business_sql'] = Db::table('business')->getLastSql();
        }
        //销售员非员工
        if($customer['sale_name'] == ''){
            $user = Db::table('users')->where('id',$customer['sales_id'])->find();
            $customer['sale_name'] = $user['name'];
            $customer['users_sql'] = Db::table('users')->getLastSql();
        }
        if( !empty($customer['brand_demand'])){
                $customer['brand_demand']   = array_values(json_decode($customer['brand_demand'],true));
        }
        $brand_ids = [];
        if( !empty($customer['brand_id'])){
                $customer['brand_id']       = array_values(json_decode($customer['brand_id'],true));
                foreach ($customer['brand_id'] as $brand_id) {
                    $brand_ids[] = intval($brand_id);
                }
        }
        
        $customer['brand_id'] = $brand_ids;
        
        if( !empty($customer['residence'])){
                $customer['residence']       = array_values(json_decode($customer['residence'],true));
        }else{
            $customer['residence'] = [];
        }
        return ['code' =>666,'msg' => '获取客户详情成功', 'data' => $customer];
    }

    /**
     * 编辑客户信息.
     * Jason ZHENG
     * 2018-06-04
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $rule = [
            "id"    => "require",
            "name|名称"=>"require|chsDash",
            "sex|性别"=>"in:0,1,3",
            // "age|年龄"=>"number|between:1,150",
            "phone|电话"=>"require|number|max:11|^1[0-9]{10}$",
            "remark|备注"=>"max:100",
            // "brand_id|品牌id"=>"require",
//            "sales_id|销售员"=>"require|number",
            // "brand_demand|品牌需求"=>"require",
//            "follow_type|更进类型"=>"require",
            "wechat|微信账号"=>"max:20",
        ];

        $post       = $request->post();
        $validate   = $this->validate($post, $rule);
        ReturnData::IfTrue($validate, 10100);
        $post['id'] = $post['user_id'];
        $customer =  Db::table("customer")
                ->where(['user_id' => $post['id']])
                ->find();
        $user = Db::table("users")
                ->where(['id' => $post['id']])
                ->find();
        
        if(empty($customer)){
            ReturnData::err(10001,[],"客户不存在！");
        }

        if(empty($user)){
            ReturnData::err(10002,[],"用户不存在！");
        }

        if($user['phone'] !== $post['phone']){
            ReturnData::err(10101,[],"手机号不能修改！");
        }

        $user_info=Session::get("user");
        if($user_info['is_business']!=0)
        {
            $business_id    = $user_info['id'];
            $store_id       = $post['store_id']=='' ? 0 : $post['store_id'];
            $staff_id       = $post['sales_id']=='' ? $user_info['id'] : $post['sales_id'];
        }elseif($user_info['shop']!=0)
        {
            $bs_info=$this->get_businessid($user_info['id']);
            $business_id=$bs_info;
            $store_id=$user_info['id'];
            $staff_id       = $post['sales_id']=='' ? $user_info['id'] : $post['sales_id'];

        }elseif($user_info['is_staff']!=0)
        {
            $bs_info=$this->getbusinessid($user_info['id']);
            $business_id=$bs_info['business_id'];
            $store_id=$bs_info['store_id'];
            $staff_id       = $post['sales_id']=='' ? $user_info['id'] : $post['sales_id'];
        }

        $post['topimageurl']= $request->post("topimageurl");
        // 启动事务
        Db::startTrans();
        try{

            Db::table("customer")
                ->where(['user_id' =>$post['id']])
                ->update([
                "store_id"=>$store_id,
                "sales_id"=>$staff_id,
                "is_toshop"=>isset($post['is_toshop'])? $post['is_toshop']:0,
                "next_visit"=>isset($post['next_visit'])? $post['next_visit']:"一天后回访",
                "remark"  =>isset($post['remark'])? $post['remark']:null
            ]);


            Db::table("customer_log")
                ->where(['user_id' => $customer['user_id'] ])
                ->update([
                "brand_demand"=>isset($post['brand_demand'])? json_encode($post['brand_demand']):null,
                "brand_id"=> isset($post['brand_id'])? json_encode($post['brand_id']):null,
                "source"=>isset($post['source'])? $post["source"]:null,
                "follow_type"=>isset($post['follow_type'])? $post['follow_type']:null,
                "follow_content"=>isset($post['follow_content'])? $post['follow_content']:null,
                "is_toshop"=>isset($post['is_toshop'])? $post['is_toshop']:0,
                "store_id"    => $store_id,
                "sales_id"=>$staff_id
            ]);

            Db::table("users")
                ->where(['id' => $customer['user_id'] ])
                ->update([
                "name"=>$post['name'],
            ]);
           
            Db::table("user_info")
                ->where(['user_id' => $customer['user_id']])
                ->update([
                "name"=>$post['name'],
                "sex"=>isset($post['sex'])? $post["sex"]:3,
                "wechat"=>isset($post['wechat'])? $post["wechat"]:null,
                "residence"=>isset($post['residence'])? json_encode($post["residence"]):null,
                "alipay"=>isset($post['alipay'])? $post["alipay"]:null,
                "topimageurl"=>isset($post['topimageurl'])? $post['topimageurl']:null
            ]); 
            
            Db::table("bankcard")
                ->where(["user_id"=>$customer['user_id']])
                ->update([
                "bankcard_id"=>isset($post['bankcard_id'])? $post["bankcard_id"]:null
            ]);
            // 提交事务
            Db::commit();    
            ReturnData::ok();
        } catch (\Exception $e) {
            // 回滚事务
            ReturnData::err(10102,[],$e->getMessage());
            Db::rollback();
        }
    }

    //客户订单列表
    public function orders(Request $request)
    { 
        $rule = [
            "user_id"    => "require",
        ];

        $post       = $request->post();
        $validate   = $this->validate($post, $rule);
        ReturnData::IfTrue($validate, 10100);

        $customer_id = $post['user_id'];
        $field = 'o.id,o.business_id,o.batchcode,o.total_price,o.payment_status, o.createtime,oi.store_id,oi.product_id,oi.product_name,p.systematics_id,p.product_condition,pf.value product_condition_value'
                    .',oi.original_price,oi.price,oi.cost_price,oi.peer_price,oi.status,sc.value status_value,oi.is_prepay,oi.deposit,oi.nursing_fee,oi.other_fee,oi.staff_id,oi.nursing_cost,oi.nursing_income'
                    .',oi.customer_name,oi.customer_id,oi.order_source,oi.is_confirm,oi.finance_confirm_time,oi.total_profit,oi.is_nursing,oi.procurement_status,ps.value procurement_value,oi.settlement_time';
        $orders = Db::table("orders")
                ->alias('o')
                ->join('orders_info oi', 'o.batchcode = oi.batchcode', 'LEFT')
                ->join('product p','oi.product_id = p.id')
                ->join('sales_condition sc','oi.status = sc.id','LEFT')
                ->join('product_fineness pf','p.product_condition = pf.id', 'LEFT')
                ->join('perchase_source ps','oi.procurement_status = ps.id','LEFT')
                ->where(['o.user_id' => $customer_id ,'o.state' => 0])
                ->order('o.createtime desc')
                ->field($field)
                ->select();

        foreach ($orders as $key => $order) {
            $prename = (new Product)->set_product_name($order['systematics_id']);
            $orders[$key]['pre_name'] = $prename['data'];
        }
        return ['code' => 666, 'msg' => 'ok', 'data' => $orders];
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
